const fileService = require('../service/file.service');
const removeAvatar = require('../utils/removeAvatar-handle');
const {APP_HOST, APP_PORT} = require('../app/config');

class FileController {
  async seaveAvatarInfo(ctx, next) {
    const {id} = ctx.user;
    const {filename, mimetype, size} = ctx.req.file;

    const result = await fileService.selectAvatarDoesItExist(id);

    if (!result.length) {
      // 保存头像信息
      await fileService.saveAvatarInfo(id, filename, mimetype, size);
    } else {
      // 更新头像信息
      const result = await fileService.updateAvatarInfo(id, filename, mimetype, size);
      // console.log(result.filename);.
      // 删除原本头像
      removeAvatar(result.filename);
    }
    
    // 将图片地址保存到用户表
    const avatarPath = `${APP_HOST}:${APP_PORT}/user/${id}/avatar`;
    await fileService.updateAvatar(id, avatarPath);

    ctx.body = '头像上传成功！';
  }
}

module.exports = new FileController();